//
//  WBOAuthViewController.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
let loginSuccessNotification = "loginSuccessNotification"

class WBOAuthViewController: WBNavigationViewController {
    
    fileprivate lazy var webView: UIWebView = {
        let webView: UIWebView = UIWebView(frame: CGRect(x: 0, y: 64, width: screenWidth, height: screenHeight-64))
        webView.delegate = self
        webView.backgroundColor = UIColor.white
        webView.scrollView.bounces = false
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        
        //加载webView
        loadLoginPage()
    }
    
    /// 设置导航条
    override func setupNavigationBar() {
        
        // 设置导航条按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(popViewController))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(popViewController))
        
    }
    
    /// pop当前self
    @objc fileprivate func popViewController() {
        self.dismiss(animated: true, completion: {})
    }
    
    /// 销毁
    deinit {
        print("oAuth bye bye")
    }

}


// MARK: - 加载数据
extension WBOAuthViewController {
    fileprivate func loadLoginPage() {
        //1. 创建url
        let url = URL(string: WBNetworkTools.sharedManager.oAuthURL)

        //2. 创建request
        let request = URLRequest(url: url!)
        
        //3. 发起request请求
        webView.loadRequest(request)
    }
}

// MARK: - UIWebViewDelegate
extension WBOAuthViewController: UIWebViewDelegate {
    
    /// 即将开始加载数据时调用的,可以在这个方法内部拦截到webView上所有的网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果我们发现 url 是 http://www.baidu.com, 就证明授权成功了,可以通过url获取code, 并且不让该页面显示, return false
        //用户登录成功之后,会跳到一个授权/取消一个页面,点击授权或者点击取消都会跳到百度, 只要是百度,都需要 return false. 再判断url中是否有code, 如果有code, 说明成功, 拿到code后续操作, 如果没有code,直接dismiss
        
        //获取url的字符串
        let urlString = request.url?.absoluteString
        print(urlString ?? "NULL")
        
        //1> 获取code授权码
        //判断url是否有百度的前缀,如果有,则说明点击的是授权或取消按钮 **微博后台设置
        if let urlString = urlString, urlString.hasPrefix(redirectURI) {
            
            //判断是授权,还是取消: 如果url中有code, 说明是授权,否则是取消
            //https://www.baidu.com/?code=140db540622297a83821a49c8952a54e
            //query = request.url?.query, 获取url中参数的部分的字符串
            
            if let query = request.url?.query, query.hasPrefix("code=") {
                //说明点击的是授权按钮, 拿到code
                let code = query.substring(from: "code=".endIndex)
                
                //2> 获取accessToken
                WBNetworkTools.sharedManager.requestAccessToken(code: code, callBack: { (accesTokenResponse) in
                    
                    //3> 拿到access_token和uid, 获取用户信息
                    // accesTokenResponse 是Any类型, 所以需要做一个类型转换
                    if var accesTokenDic = accesTokenResponse as? [String: Any],
                        let uid = accesTokenDic["uid"] as? String,
                        let access_token = accesTokenDic["access_token"] as? String {
                        
                        // 4> 访问请求（Token)
                        WBNetworkTools.sharedManager.reqeustUserInfo(uid: uid, access_token: access_token, callBack: { (userInfoDic) in
                            
                            //5> 保存用户信息和accessToken的信息, 把两个字典合并
                            if let userInfoDic = userInfoDic as? [String: Any] {
                                
                                for (key,value) in userInfoDic {
                                    accesTokenDic[key] = value
                                }
                                
                                //打印将要存储的用户信息字典
                                print(accesTokenDic)
                                
                                //保存用户信息
                                WBUserAccount.shared.saveUserInfo(dict: accesTokenDic)
                                self.popViewController()
                                
                                //通知其它controller, 登录成功了
                                //3.0新的写法: notifcation的name不能直接传字符
                                //**通知一发  所有继承和WBBaseViewController自己都会响应
                                NotificationCenter.default.post(name: NSNotification.Name(rawValue: loginSuccessNotification), object: nil)
                                
                            }else{
                                self.popViewController()
                            }
                        })
                        
                    }else{
                        self.popViewController()
                    }
                })
            } else {
                print("点击了取消按钮")
                self.popViewController()
            }
            return false
        }
        
        return true
        
    }
    
    /// 网页数据加载完成之后调用的,在该方法里面可以实现JS注入
    func webViewDidFinishLoad(_ webView: UIWebView) {
        let jsString = "document.getElementById('userId').value='13148939017';document.getElementById('passwd').value='qwq137360'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
}
